﻿using System;
using System.IO;
using LibGit2Sharp;
using LibGit2Sharp.Handlers;

static class InstallerDownloader
{
    public static void cloneSoftWareInstaller(string name)
    {

        string repoUrl = "https://gitcode.com/fengfei1989/osi_repository.git";
        string remotePath = Path.Join("windows" ,name + ".ei");
        string localPath = Path.Join("C:\\osi\\InstallerTemp", name);
        string branchName = "master";

        try
        {
            Console.WriteLine($"Downloading {remotePath} from {repoUrl}...");

            // 创建临时目录
            string tempDir = "C:\\osi\\Temp";
            Directory.CreateDirectory(tempDir);

            // 配置精简克隆选项
            var cloneOptions = new CloneOptions(new FetchOptions
            {
                Prune = true,
                TagFetchMode = TagFetchMode.None
            })
            {
                BranchName = branchName,
                Checkout = false
            };

            // 执行精简克隆
            Repository.Clone(repoUrl, tempDir, cloneOptions);

            // 获取文件内容
            using (var repo = new Repository(tempDir))
            {
                var commit = repo.Branches[branchName]?.Tip;
                if (commit == null)
                {
                    throw new Exception($"Branch {branchName} not found");
                }

                var treeEntry = commit[remotePath];
                if (treeEntry == null)
                {
                    throw new FileNotFoundException($"File {remotePath} not found in repository");
                }

                using (var blobStream = ((Blob)treeEntry.Target).GetContentStream())
                using (var fileStream = File.Create(localPath))
                {
                    blobStream.CopyTo(fileStream);
                }
            }

            Console.WriteLine($"File successfully saved to: {localPath}");
        }
        catch (LibGit2SharpException ex)
        {
            Console.WriteLine($"Git error: {ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }

}